package com.fsnbigdata.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fsnbigdata.util.IPToAddressUtil.DataBlock;
import com.fsnbigdata.util.IPToAddressUtil.DbConfig;
import com.fsnbigdata.util.IPToAddressUtil.DbSearcher;
import com.fsnbigdata.util.IPToAddressUtil.Util;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author cqz
 * @title: IPTOAddress
 * @projectName fsnbigdata
 * @description: TODO
 * @date 2019/4/2515:11
 */
public class IPTOAddress {

    //获取当前客户端ip
    public static String getIP(HttpServletRequest request) throws Exception{
        String ip = request.getHeader("x-forwarded-for");
        System.out.println("x-forwarded-for ip: " + ip);
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            System.out.println("Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            System.out.println("WL-Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            System.out.println("HTTP_CLIENT_IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
            System.out.println("X-Real-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            System.out.println("getRemoteAddr ip: " + ip);
        }
        System.out.println("获取客户端ip: " + ip);
        return ip;
    }

    //获取当前主机名
    public static String getAddr(HttpServletRequest request) throws Exception{
        String addr = request.getRemoteHost();
        return addr;
    }

    //通过ip获取国家，省份，城市
    public static String addr(String ip){
        String ips = ip;
        String addr = getCityInfo(ips);
        String address [] = addr.split("\\|");
        StringBuffer stringBuffer = new StringBuffer();
        if (!Objects.equals(address[0],"0")){
            stringBuffer.append(address[0]);
        }
        if (!Objects.equals(address[2],"0")){
            stringBuffer.append(address[2]);
        }
        stringBuffer.append(address[3]);
        System.err.println("----->>"+"ip "+ips+" 所在城市为："+stringBuffer.toString());
        return stringBuffer.toString();
    }

    public static void inputstreamtofile(InputStream ins,File file){
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    public static String getCityInfo(String ip){
//        String dbPath = IPTOAddress.class.getClassLoader().getResource("static/ip2region.db").getPath();
//        System.out.println("------------>>  daPath = "+dbPath);
        String dbPath = null;
        InputStream reader = null;
        File file = null;
        try {
//            dbPath = new DefaultResourceLoader().getResource("classpath:/ip2region.db").getFile().getPath();
            reader = new ClassPathResource("ip2region.db").getInputStream();
            file= new File("ip2region1.db");
            inputstreamtofile(reader,file);
        }catch (Exception e){
            System.out.println("没有找到文件"+e.getMessage());
        }
        System.out.println(reader);

        if (file.exists() == false){
            System.out.println("无效的文件ip2region.db");
        }
        //查询算法
        int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
        //DbSearcher.BINARY_ALGORITHM //Binary
        //DbSearcher.MEMORY_ALGORITYM //Memory

        try{
            DbConfig dbConfig = new DbConfig();
            DbSearcher dbSearcher = new DbSearcher(dbConfig,file);
            Method method = null;
            switch (algorithm){
                case DbSearcher.BTREE_ALGORITHM:
                    method = dbSearcher.getClass().getMethod("btreeSearch", String.class);
                    break;
                case DbSearcher.BINARY_ALGORITHM:
                    method = dbSearcher.getClass().getMethod("binarySearch", String.class);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    method = dbSearcher.getClass().getMethod("memorySearch", String.class);
                    break;
            }

            DataBlock dataBlock = null;
            if (Util.isIpAddress(ip) == false){
                System.out.println("无效的ip地址");
            }
            dataBlock = (DataBlock)method.invoke(dbSearcher,ip);
            return dataBlock.getRegion();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
